<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6" v-for="(item, index) in statusStats" :key="index">
        <el-card :body-style="{ padding: '10px' }">
          <div class="card-title">{{ item.title }}</div>
          <div class="card-number">{{ item.count }}</div>
          <div class="card-desc">{{ item.desc }}</div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>设备状态分布</span>
          </div>
          <div ref="statusChart" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>各车间设备状态分布</span>
          </div>
          <div ref="workshopChart" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card style="margin-top: 20px;">
      <div slot="header">
        <span>设备状态变更</span>
      </div>

      <el-form :inline="true" :model="queryParams" ref="queryForm" size="small" style="margin-bottom: 15px;">
        <el-form-item label="设备编码" prop="equipmentCode">
          <el-input v-model="queryParams.equipmentCode" placeholder="请输入设备编码" clearable style="width: 200px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="设备状态" prop="equipmentStatus">
          <el-select v-model="queryParams.equipmentStatus" placeholder="请选择设备状态" clearable style="width: 150px">
            <el-option label="空闲" value="0" />
            <el-option label="在用" value="1" />
            <el-option label="维修中" value="2" />
            <el-option label="报废" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备编码" align="center" prop="equipmentCode" />
        <el-table-column label="设备名称" align="center" prop="equipmentName" />
        <el-table-column label="设备类型" align="center" prop="equipmentTypeName" />
        <el-table-column label="设备位置" align="center" prop="location" />
        <el-table-column label="设备状态" align="center" prop="equipmentStatus">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.equipmentStatus === '0'" type="success">空闲</el-tag>
            <el-tag v-else-if="scope.row.equipmentStatus === '1'" type="warning">在用</el-tag>
            <el-tag v-else-if="scope.row.equipmentStatus === '2'" type="danger">维修中</el-tag>
            <el-tag v-else-if="scope.row.equipmentStatus === '3'" type="info">报废</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleChangeStatus(scope.row)"
            >变更状态</el-button>
            <el-button
              size="mini"
              type="info"
              @click="handleViewStatusHistory(scope.row)"
            >历史记录</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    
    <!-- 状态变更弹窗 -->
    <el-dialog title="变更设备状态" :visible.sync="statusDialogVisible" width="500px" append-to-body>
      <el-form ref="statusForm" :model="statusForm" :rules="statusRules" label-width="100px">
        <el-form-item label="设备编码">
          <span>{{ statusForm.equipmentCode }}</span>
        </el-form-item>
        <el-form-item label="设备名称">
          <span>{{ statusForm.equipmentName }}</span>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag v-if="statusForm.oldStatus === '0'" type="success">空闲</el-tag>
          <el-tag v-else-if="statusForm.oldStatus === '1'" type="warning">在用</el-tag>
          <el-tag v-else-if="statusForm.oldStatus === '2'" type="danger">维修中</el-tag>
          <el-tag v-else-if="statusForm.oldStatus === '3'" type="info">报废</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </el-form-item>
        <el-form-item label="新状态" prop="newStatus">
          <el-select v-model="statusForm.newStatus" placeholder="请选择新状态">
            <el-option label="空闲" value="0" />
            <el-option label="在用" value="1" />
            <el-option label="报废" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="变更原因" prop="changeReason">
          <el-input v-model="statusForm.changeReason" type="textarea" placeholder="请输入变更原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statusDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitStatusChange">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 历史记录弹窗 -->
    <el-dialog title="设备状态历史" :visible.sync="historyDialogVisible" width="800px" append-to-body>
      <el-table :data="statusHistoryList" style="width: 100%">
        <el-table-column prop="changeTime" label="变更时间" width="180" />
        <el-table-column label="原状态" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.oldStatus === '0'" type="success">空闲</el-tag>
            <el-tag v-else-if="scope.row.oldStatus === '1'" type="warning">在用</el-tag>
            <el-tag v-else-if="scope.row.oldStatus === '2'" type="danger">维修中</el-tag>
            <el-tag v-else-if="scope.row.oldStatus === '3'" type="info">报废</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="新状态" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.newStatus === '0'" type="success">空闲</el-tag>
            <el-tag v-else-if="scope.row.newStatus === '1'" type="warning">在用</el-tag>
            <el-tag v-else-if="scope.row.newStatus === '2'" type="danger">维修中</el-tag>
            <el-tag v-else-if="scope.row.newStatus === '3'" type="info">报废</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="操作人" width="120" />
        <el-table-column prop="changeReason" label="变更原因" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="historyDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { listEquipment } from "@/api/sb/equipment";
import { listStatusLogs, listEquipmentStatusLogs, changeEquipmentStatus, getEquipmentStatusStats } from "@/api/sb/equipmentStatus";

export default {
  name: "EquipmentStatus",
  data() {
    return {
      // 加载状态
      loading: true,
      // 设备状态统计
      statusStats: [
        { title: '设备总数', count: 0, desc: '设备总量' },
        { title: '空闲设备', count: 0, desc: '状态为空闲的设备' },
        { title: '使用中设备', count: 0, desc: '状态为使用中的设备' },
        { title: '维修中设备', count: 0, desc: '状态为维修中的设备' }
      ],
      // 图表实例
      statusChart: null,
      workshopChart: null,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 设备列表
      equipmentList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentCode: null,
        equipmentStatus: null
      },
      // 状态变更弹窗
      statusDialogVisible: false,
      // 状态变更表单
      statusForm: {
        equipmentId: null,
        equipmentCode: '',
        equipmentName: '',
        oldStatus: '',
        newStatus: '',
        changeReason: ''
      },
      // 表单校验
      statusRules: {
        newStatus: [
          { required: true, message: "新状态不能为空", trigger: "change" }
        ],
        changeReason: [
          { required: true, message: "变更原因不能为空", trigger: "blur" },
          { max: 500, message: '变更原因不能超过500个字符', trigger: 'blur' }
        ]
      },
      // 历史记录弹窗
      historyDialogVisible: false,
      // 状态历史列表
      statusHistoryList: []
    };
  },
  created() {
    this.getList();
    this.getStatsData();
  },
  mounted() {
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    if (this.statusChart) {
      this.statusChart.dispose();
      this.statusChart = null;
    }
    if (this.workshopChart) {
      this.workshopChart.dispose();
      this.workshopChart = null;
    }
  },
  methods: {
    /** 查询设备状态列表 */
    getList() {
      this.loading = true;
      listEquipment(this.queryParams).then(response => {
        this.equipmentList = response.rows;
        this.total = parseInt(response.total) || 0;
        this.loading = false;
      }).catch(error => {
        console.error("获取设备状态列表失败", error);
        this.equipmentList = [];
        this.total = 0;
        this.loading = false;
      });
    },
    /** 获取统计数据 */
    getStatsData() {
      getEquipmentStatusStats().then(response => {
        const data = response.data || {};
        
        // 更新数字卡片
        this.statusStats[0].count = data.totalCount || 0;
        this.statusStats[1].count = data.idleCount || 0;
        this.statusStats[2].count = data.inUseCount || 0;
        this.statusStats[3].count = data.repairingCount || 0;
        
        // 准备图表数据
        const statusData = [
          { name: '空闲', value: data.idleCount || 0 },
          { name: '在用', value: data.inUseCount || 0 },
          { name: '维修中', value: data.repairingCount || 0 },
          { name: '报废', value: data.scrapCount || 0 }
        ];
        
        // 初始化图表
        this.$nextTick(() => {
          this.initStatusChart(statusData);
          this.initWorkshopChart(data.workshopStats || []);
        });
      });
    },
    /** 初始化状态分布图表 */
    initStatusChart(data) {
      this.statusChart = echarts.init(this.$refs.statusChart);
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 0
        },
        series: [
          {
            name: '设备状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ]
      };
      this.statusChart.setOption(option);
    },
    /** 初始化车间设备分布图表 */
    initWorkshopChart(data) {
      this.workshopChart = echarts.init(this.$refs.workshopChart);
      
      // 准备数据
      const workshops = [];
      const idleData = [];
      const inuseData = [];
      const repairData = [];
      const scrapData = [];
      
      data.forEach(item => {
        workshops.push(item.workshop);
        idleData.push(item.idle_count);
        inuseData.push(item.inuse_count);
        repairData.push(item.repair_count);
        scrapData.push(item.scrap_count);
      });
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['空闲', '在用', '维修中', '报废'],
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: workshops
          }
        ],
        yAxis: [
          {
            type: 'value',
            minInterval: 1
          }
        ],
        series: [
          {
            name: '空闲',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: idleData
          },
          {
            name: '在用',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: inuseData
          },
          {
            name: '维修中',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: repairData
          },
          {
            name: '报废',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: scrapData
          }
        ]
      };
      
      this.workshopChart.setOption(option);
    },
    /** 重置图表大小 */
    resizeCharts() {
      if (this.statusChart) {
        this.statusChart.resize();
      }
      if (this.workshopChart) {
        this.workshopChart.resize();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 选择条目发生变化 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.equipmentId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 查看设备状态历史 */
    handleViewStatusHistory(row) {
      this.statusHistoryList = [];
      this.historyDialogVisible = true;
      listEquipmentStatusLogs(row.equipmentId).then(response => {
        this.statusHistoryList = response.data;
      });
    },
    /** 变更设备状态 */
    handleChangeStatus(row) {
      // 检查设备当前是否处于维修中状态
      if (row.equipmentStatus === '2') {
        this.$modal.msgError("设备当前处于维修中状态，不能手动修改，必须通过维修完成流程自动转换");
        return;
      }
      
      this.statusForm = {
        equipmentId: row.equipmentId,
        equipmentCode: row.equipmentCode,
        equipmentName: row.equipmentName,
        oldStatus: row.equipmentStatus,
        newStatus: '',
        changeReason: ''
      };
      this.statusDialogVisible = true;
    },
    /** 提交状态变更 */
    submitStatusChange() {
      this.$refs["statusForm"].validate(valid => {
        if (valid) {
          // 如果新旧状态相同，提示用户
          if (this.statusForm.oldStatus === this.statusForm.newStatus) {
            this.$modal.msgError("新状态不能与当前状态相同");
            return;
          }
          
          // 检查是否试图手动将设备状态改为维修中
          if (this.statusForm.newStatus === '2') {
            this.$modal.msgError("不能手动将设备状态改为维修中，必须通过报修流程自动转换");
            return;
          }
          
          changeEquipmentStatus(
            this.statusForm.equipmentId, 
            this.statusForm.newStatus, 
            this.statusForm.changeReason
          ).then(response => {
            this.$modal.msgSuccess("状态变更成功");
            this.statusDialogVisible = false;
            this.getList();
            this.getStatsData();
          }).catch(error => {
            this.$modal.msgError("状态变更失败: " + error.message);
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.card-title {
  font-size: 14px;
  color: #666;
}
.card-number {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin: 10px 0;
}
.card-desc {
  font-size: 12px;
  color: #999;
}
</style> 